//
//  CountdownViewModel.m
//  SadjAppClient
//
//  Created by 送爱到家 on 2018/1/4.
//  Copyright © 2018年 huang. All rights reserved.
//

#import "CountdownTimer.h"
//#import "PublicDefine.h"

@interface CountdownTimer()
@property(nonatomic)CGFloat lastTimer;
//@property(nonatomic,strong)RACDisposable *disposable;     //计时器
@property(nonatomic,strong)dispatch_source_t timer;
@end

@implementation CountdownTimer
-(instancetype)init
{
    self = [super init];
    if (self) {
        self.allTimer = 60;
        self.interval = 1;
//        self.scheduler = [RACScheduler currentScheduler];
        
    }
    return self;
}


-(void)startRuning:(void (^)(CGFloat))block withTimerEnd:(dispatch_block_t)endBlock
{
    [self startRuningWihtStartTimer:self.allTimer withBlock:block withTimerEnd:endBlock];
    
}
-(void)startRuningWihtStartTimer:(CGFloat)startTimer  withBlock:(void (^)(CGFloat timer))block withTimerEnd:(dispatch_block_t)endBlock
{
    [self stopRuning];
    if (startTimer >= self.allTimer) {
        startTimer = self.allTimer;
    }
    else if(startTimer < 0)
    {
        startTimer = 0;
    }
    self.lastTimer = startTimer;
    __weak typeof(self)weakself = self;
//    WeakSelf(self);
//    _disposable  = [[RACSignal interval:fabs(self.interval) onScheduler:self.scheduler?:[RACScheduler mainThreadScheduler]] subscribeNext:^(NSDate * _Nullable x) {
//        weakself.lastTimer -= weakself.interval;
//
//        if (weakself.lastTimer >= weakself.allTimer || weakself.lastTimer <= 0 ) {
//            if (endBlock) {
//                endBlock();
//            }
//            [weakself.disposable dispose];
//
//        }
//        else
//        {
//            if (block) {
//                block(weakself.lastTimer);
//            }
//        }
//
//    }];
    
//    dispatch_source_t _timer; // 必须创建成全局变量，否则执行一次就会被release掉。
    
  
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.queue?:dispatch_get_main_queue());
    
    /**
     *  dispatch_source_set_timer(dispatch_source_t source,
     *  dispatch_time_t start,
     *  uint64_t interval,
     *  uint64_t leeway);
     *
     *  params:
     *      start: 定时器开始时间,可以通过dispatch_time和dispatch_walltime函数来创建，也可以使用常量DISPATCH_TIME_NOW和DISPATCH_TIME_FOREVER
     *      interval: 间隔时间，1.0 * NSEC_PER_SEC 一秒
     *  leeway: 计时器触发的精准程度
     */
    dispatch_source_set_timer(_timer, DISPATCH_TIME_NOW, fabs(self.interval) * NSEC_PER_SEC, 0);
    
    // 计时器的触发block
    dispatch_source_set_event_handler(_timer, ^{
        weakself.lastTimer -= weakself.interval;
        
        if (weakself.lastTimer >= weakself.allTimer || weakself.lastTimer <= 0 ) {
            if (endBlock) {
                endBlock();
            }
             dispatch_source_cancel(weakself.timer);
            
        }
        else
        {
            if (block) {
                block(weakself.lastTimer);
            }
        }

    });
    
    // 计时器cancel的时候触发的block
    dispatch_source_set_cancel_handler(_timer, ^{
        
        NSLog(@"cancel");
    });
    
    // 因为dispatch_source启动时默认是挂起状态的，需要手动启动。
    dispatch_resume(_timer);

    
}

-(void)stopRuning
{
//    if (self.disposable) {
//        [self.disposable dispose];
//    }
    if (self.timer) {
        dispatch_source_cancel(self.timer);
    }
    
}
-(void)dealloc
{
    [self stopRuning];
}

@end
